package com.kde.crisisdepalabras;


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

public class ServiceTask extends AsyncTask<String, Integer, JSONArray>
{

	private TaskComplete taskComplete;
	
	@Override
	protected JSONArray doInBackground(String... params) 
	{
		try 
		{
			URL toRequest = new URL(params[0]);
			HttpURLConnection urlConnection = (HttpURLConnection)toRequest.openConnection();
			urlConnection.setConnectTimeout(10000);
			urlConnection.setReadTimeout(10000);
			int statusCode = urlConnection.getResponseCode();
			
			if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED)
			{
				
			}
			else if (statusCode != HttpURLConnection.HTTP_OK)
			{
				Log.e(getClass().getName(), "405, 404, 500");
			}
			
			InputStream in = new BufferedInputStream(urlConnection.getInputStream());
			String json = new Scanner(in).useDelimiter("\\A").next();
			
			JSONArray jsonObject = new JSONArray(json);
			
			return jsonObject;
		}
		catch (IOException ex) 
		{
			Log.e(getClass().getName(), ex.getMessage());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;		
	}
	
	@Override
	protected void onPostExecute(JSONArray result) 
	{		
		if (result != null)
		{
			taskComplete.onComplete(result);
		}
		super.onPostExecute(result);
	}
	
	@Override
	protected void onProgressUpdate(Integer... values) 
	{
		// TODO Auto-generated method stub
		super.onProgressUpdate(values);
	}

	public TaskComplete getTaskComplete() {
		return taskComplete;
	}

	public void setTaskComplete(TaskComplete taskComplete) {
		this.taskComplete = taskComplete;
	}


}
